package com.bjsj.pro.tools;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import com.bjsj.pro.interfaces.OnSelectTimeCallBack;
import com.bjsj.pro.R;
import com.bjsj.pro.base.BaseUiAdapter;
import com.bjsj.pro.base.view.NetworkLayout;

import com.bjsj.pro.view.DialogManager;
import com.bjsj.pro.view.NineGridView.ImageInfo;
import com.bjsj.pro.view.NineGridView.ImagePreviewActivity;
import com.bjsj.pro.view.PrimaryDialog;
import com.bjsj.pro.view.SelectDialog;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by Nevermore on 2016/7/25.
 */
public class GlobalTools<T> {


    private static GlobalTools instance = null;

    /**
     * 构造方法描述:私有构造方法
     */
    private GlobalTools() {
    }


    /**
     * 构造方法描述:获取实例
     *
     * @return 返 回 类 型:Utils
     */
    public synchronized static GlobalTools getInstance() {
        if (instance == null) {
            instance = new GlobalTools();
        }
        return instance;
    }


    private boolean isLog = true;

    public void logD(String msg) {
        if (isLog) {
            Log.d("============LOG.D:", msg);
        }
    }


    /**
     * 获得独一无二的Psuedo ID
     **/
    public String getuniqueId() {
        String serial = null;

        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        try {
            serial = Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    /**
     * 构造方法描述:xml布局单位换算dp转px
     *
     * @param context
     * @param dp
     * @return 返 回 类 型:int
     */
    public int Dp2Px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    /**
     * 构造方法描述:获取手机状态栏的高度
     *
     * @param context
     * @return 返 回 类 型:int
     */
    public int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
//    第一种：判断手机是否有物理按键，有就没有导航栏，反之就有（这个有点问题，逻辑不严谨，4.0以上所有手机都可以显示NavigationBar，只是手机厂家屏蔽了）。

    public static boolean checkDeviceHasNavigationBar(Context activity) {
        //通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
        boolean hasMenuKey = ViewConfiguration.get(activity)
                .hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap
                .deviceHasKey(KeyEvent.KEYCODE_BACK);

        if (!hasMenuKey && !hasBackKey) {
            // 做任何自己需要做的,这个设备有一个导航栏
            return true;
        }
        return false;
    }

    /**
     * @方法说明：获取APP版本名
     * @参数详解：context上下文引用
     * @作者：StriveDoby
     */
    public String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    /**
     * @方法说明：获取APP版本号
     * @参数详解：context上下文引用
     * @作者：StriveDoby
     */
    public int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    private PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    /**
     * 获取当前应用程序的包名
     *
     * @param context 上下文对象
     * @return 返回包名
     */
    public String getAppProcessName(Context context) {
        //当前应用pid
        int pid = android.os.Process.myPid();
        //任务管理类
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //遍历所有应用
        List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.pid == pid)//得到当前应用
                return info.processName;//返回包名
        }
        return "";
    }

    /**
     * 选择对话框
     **/
    public SelectDialog showSelcetDialog(Activity context, String title, SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(context, R.style.transparentFrameWindowStyle,
                listener, names);

        dialog.setTitle(title);
        if (!context.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    /**
     * @方法说明：字面上的意思
     * @参数详解：type,选择Toast显示时间长短;context,上下文引用;hint,Toast内容
     * @作者：StriveDoby
     */

    public void showToast(Context context, String hint) {
        // getShortToastByString(context, hint);
        Toast.makeText(context, hint, Toast.LENGTH_SHORT).show();
    }

    public void showToastCenter(Context context, String hint) {
        // getShortToastByString(context, hint);
        Toast toast = Toast.makeText(context, hint, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();

    }

    /**
     * 构造方法描述:获取手机屏幕宽
     *
     * @param context
     * @return 返 回 类 型:int
     */
    public int getPhoneWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;// 得到屏幕真实宽度;
    }

    //获取底部状态栏的高度
    public int getNavigationBarHeight(Context context) {

        Resources resources = context.getResources();

        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");

        int height = resources.getDimensionPixelSize(resourceId);


        return height;

    }

    /**
     * @param context
     * @param :       一行显示多少张图片
     * @return
     */
    public int getImageWith(Context context) {
        int widthPixels = getPhoneWidth(context);

        Log.e("tuijian", "gridViewWidth=" + widthPixels);

        // 屏幕真实宽度减去网格视图左右端的边距15dp再减去网格视图间的间距，除以所需的列数，得到真实的自定义网格视图的宽度
        int gridViewWidth = widthPixels - 2 * ((int) (Dp2Px(context, 10) + 2 * Dp2Px(context, 15))); // 10表示2张图片间距，15表示左右间距（mar）

        return gridViewWidth / 3;// 将得到的宽度平分2分，即一行显示2张图片
    }

    /**
     * 构造方法描述:获取手机屏幕高
     *
     * @param context
     * @return 返 回 类 型:int
     */
    public int getPhoneHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;// 得到屏幕真实高度;
    }


    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {

            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();

            return isMatch;
        }
    }

    public boolean isMobile(String mobile) {
        String regex = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    /*** 验证电话号码
     * @return 如果是符合格式的字符串, 返回 <b>true </b>,否则为 <b>false </b>
     */
    public static boolean IsTelephone(String str) {
        String regex = "^0(10|2[0-5789]-|\\d{3})-?\\d{7,8}$";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    //判断身份证输入是否合理
    public static boolean verForm(String num) {
        String reg = "^\\d{15}$|^\\d{17}[0-9Xx]$";
        if (!num.matches(reg)) {
            return false;
        }
        return true;
    }

    //判断身份证最后一位
    public static boolean verify(char[] id) {
        int sum = 0;
        int w[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        char[] ch = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        for (int i = 0; i < id.length - 1; i++) {
            sum += (id[i] - '0') * w[i];
        }
        int c = sum % 11;
        char code = ch[c];
        char last = id[id.length - 1];
        last = last == 'x' ? 'X' : last;
        return last == code;
    }


    /**
     * 提示对话框
     *
     * @param /context上下文；title标题；content,内容；isCancelable，点击空白区域是否消息；ok，点击确定监听；
     **/
    public void showNormalDialog(final Context context, String title, String content, boolean isCancelable, DialogInterface
            .OnClickListener ondialog) {
        new AlertDialog.Builder(context)
                .setTitle(title)
                .setMessage(content)
                .setCancelable(isCancelable)
                .setPositiveButton("确定", ondialog)
                .setNegativeButton("取消", null)
                .show();
    }

    //缓存微信进入微信回调后的类型
    public void setWxType(Context context,boolean isType)
    {
        SharedPreferences tag_wx = GlobalTools.getInstance().getSpInstance(context, "TAG_WX");
        tag_wx.edit().putBoolean("isType",isType).commit();
    }

    /**
     * 格式化后台返回的log类型时间
     **/
    public String dataTime(long longStr)
    {
        if (String.valueOf(longStr).length() == 10) {
            longStr = longStr * 1000;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm");
        // long lt = new Long(longStr);
        Date date = new Date(longStr);
        String retTime=simpleDateFormat.format(date);
        return retTime;
    }

    /**
     * 传入一个毫秒数，得到具体天数，小时，分钟，秒
     **/
    public String reSetTime(long ms) {
        int day = 0;
        int hour;

        if (ms >= 1000 * 60 * 60 * 24) {
            day = (int) (ms / (1000 * 60 * 60 * 24));
            hour = (int) ((ms % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        } else {
            hour = (int) (ms / (1000 * 60 * 60));
        }
        int minute = (int) ((ms % (1000 * 60 * 60)) / (1000 * 60));
        int second = (int) ((ms % (1000 * 60)) / 1000);
        int millisecond = (int) (ms % 1000);

        if (day > 0) {
            return day + "天" + hour + "小时" + minute + "分钟";
        } else {
            if (hour != 0) {
                return hour + "小时" + minute + "分钟" + second + "秒";
            } else {
                return minute + "分钟" + second + "秒";
            }
        }

    }

    /**
     * 计算当前时间是否大于传入入的时间
     * 大于true,小于false
     **/
    public boolean isTime(String time) throws ParseException {
        long currentTimeMillis = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt2 = sdf.parse(time);
        long lTime = dt2.getTime();
        if (currentTimeMillis > lTime) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 字符串的日期格式的计算(相差多少年)
     */
    public int daysBetween(String smdate, String bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24) / 360;

        return Integer.parseInt(String.valueOf(between_days));
    }


    /**
     * 设置状态栏
     **/
    public void setSatuBar(View view, Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int statusBarHeight = GlobalTools.getInstance().getStatusBarHeight(activity);
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            layoutParams.height = statusBarHeight;
            view.setLayoutParams(layoutParams);
            view.setVisibility(View.VISIBLE);
        } else {
            view.setVisibility(View.GONE);
        }
    }

    /**
     * 判断字符串不为空
     **/
    public boolean stringIsOk(String content) {


        if (content != null && !TextUtils.isEmpty(content) && !TextUtils.equals(content, "null")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 发送广播
     **/
    public void sendBroUtils(Context context, String broName, String key, String vale) {
        Intent intent = new Intent(broName);
        intent.putExtra(key, vale);
        context.sendBroadcast(intent);
    }


    /**
     * 选择对话框
     **/
    public SelectDialog showSelectDialog(Activity context, String title, SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(context, R.style
                .transparentFrameWindowStyle,
                listener, names);

        dialog.setTitle(title);
        if (!context.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }


    /**
     * 选择对话框
     **/
    public PrimaryDialog showPrimaryDialog(Activity context, PrimaryDialog.PrimaryDialogListener listener) {
        PrimaryDialog dialog = new PrimaryDialog(context,listener
                );
        //dialog.setTitle(title);
        if (!context.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }


    /**
     * 判定是否安装某个APP
     **/
    public boolean isAppInstalled(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        List<String> pName = new ArrayList<String>();
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);
    }

    public void showProgress(Context context) {
        DialogManager.INSTANCE.showProgressDialog(context);
    }

    public void hideProgress() {
        DialogManager.INSTANCE.dismiss();
    }


    public SharedPreferences getSpInstance(Context context, String spName) {

        return context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    }

    /**
     * desc:保存对象
     *
     * @param context
     * @param obj     要保存的对象，只能保存实现了serializable的对象
     *                modified:
     */
    public void saveObject(Context context, String key, String spName, Object obj) {
        try {
            // 保存对象
            SharedPreferences.Editor sharedata = context.getSharedPreferences(spName, 0).edit();
            //先将序列化结果写到byte缓存中，其实就分配一个内存空间
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(bos);
            //将对象序列化写入byte缓存
            os.writeObject(obj);
            //将序列化的数据转为16进制保存
            String bytesToHexString = bytesToHexString(bos.toByteArray());
            //保存该16进制数组
            sharedata.putString(key, bytesToHexString);
            sharedata.commit();
            Log.e("==================", "保存obj成功");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("==================", "保存obj失败");
        }
    }

    /**
     * desc:将数组转为16进制
     *
     * @param bArray
     * @return modified:
     */
    public String bytesToHexString(byte[] bArray) {
        if (bArray == null) {
            return null;
        }
        if (bArray.length == 0) {
            return "";
        }
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    public Object readObject(Context context, String key, String spName) {
        try {
            SharedPreferences sharedata = context.getSharedPreferences(spName, 0);
            if (sharedata.contains(key)) {
                String string = sharedata.getString(key, "");
                if (TextUtils.isEmpty(string)) {
                    return null;
                } else {
                    //将16进制的数据转为数组，准备反序列化
                    byte[] stringToBytes = StringToBytes(string);
                    ByteArrayInputStream bis = new ByteArrayInputStream(stringToBytes);
                    ObjectInputStream is = new ObjectInputStream(bis);
                    //返回反序列化得到的对象
                    Object readObject = is.readObject();
                    return readObject;
                }
            }
        } catch (StreamCorruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //所有异常返回null
        return null;

    }

    /**
     * desc:将16进制的数据转为数组
     *
     * @param data
     * @return modified:
     */
    public byte[] StringToBytes(String data) {
        String hexString = data.toUpperCase().trim();
        if (hexString.length() % 2 != 0) {
            return null;
        }
        byte[] retData = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i++) {
            int int_ch;  // 两位16进制数转化后的10进制数
            char hex_char1 = hexString.charAt(i); ////两位16进制数中的第一位(高位*16)
            int int_ch3;
            if (hex_char1 >= '0' && hex_char1 <= '9')
                int_ch3 = (hex_char1 - 48) * 16;   //// 0 的Ascll - 48
            else if (hex_char1 >= 'A' && hex_char1 <= 'F')
                int_ch3 = (hex_char1 - 55) * 16; //// A 的Ascll - 65
            else
                return null;
            i++;
            char hex_char2 = hexString.charAt(i); ///两位16进制数中的第二位(低位)
            int int_ch4;
            if (hex_char2 >= '0' && hex_char2 <= '9')
                int_ch4 = (hex_char2 - 48); //// 0 的Ascll - 48
            else if (hex_char2 >= 'A' && hex_char2 <= 'F')
                int_ch4 = hex_char2 - 55; //// A 的Ascll - 65
            else
                return null;
            int_ch = int_ch3 + int_ch4;
            retData[i / 2] = (byte) int_ch;//将转化后的数放入Byte里
        }
        return retData;
    }


    /***
     * RecyclerView的布局管理器
     *
     * **/
    public LinearLayoutManager getLinearHorizontalLM(Context context, int type) {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);

        switch (type) {
            case Configs.LM_HORIZONTAL:
                //横向布局
                linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                break;
            case Configs.LM_VERTICAL:
                //垂直布局
                linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                break;
        }

        return linearLayoutManager;
    }

    /**
     * 设置极光推送别别名
     * alias：别名
     * action：类型;action==2,设置新的别名；action==3，删除部分别名；4，删除所有
     * sequence：参数没搞懂干什么的，先随便填
     */

/*
    public void setJpAlias(Context context, String alias, int action, int sequence) {
        //设置极光推送别名
        System.out.println("=================alias:" + alias);
        TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
        tagAliasBean.action = action;
        tagAliasBean.alias = alias;
        tagAliasBean.isAliasAction = true;

        TagAliasOperatorHelper.getInstance().handleAction(context, sequence, tagAliasBean);
    }
*/

    /***
     * 初始化上下拉刷新控件初始状态
     * refresh:是否能了刷新
     *refresh：是否能下拉刷新
     * **/

    public void initRefreshLayout(RefreshLayout refreshLayoutMyOrder, boolean refresh, boolean loadMore) {
        ClassicsHeader mClassicsHeader;
        int delta = new Random().nextInt(7 * 24 * 60 * 60 * 1000);
        mClassicsHeader = (ClassicsHeader) refreshLayoutMyOrder.getRefreshHeader();

        mClassicsHeader.setLastUpdateTime(new Date(System.currentTimeMillis() - delta));

        mClassicsHeader.setTimeFormat(new SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA));
        mClassicsHeader.setTimeFormat(new DynamicTimeFormat("更新于 %s"));

        //设置下来主题样式，第一参数是背景颜色，第二个是字体颜色
        refreshLayoutMyOrder.setPrimaryColorsId(android.R.color.white, android.R.color.black);

        refreshLayoutMyOrder.setEnableLoadMore(loadMore);
        refreshLayoutMyOrder.setEnableRefresh(refresh);
    }


    private OnSelectTimeCallBack onSelectTimeCallBack;

    public void setOnSelectTimeCallBack(OnSelectTimeCallBack onSelectTimeCallBack) {
        this.onSelectTimeCallBack = onSelectTimeCallBack;
    }

    /***
     * 是否设置选择最小时间范围
     * **/
    public void showSelectTime(final Activity activity, boolean minTime) {
        Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);

        /**
         * 构造函数原型：
         * public DatePickerDialog (Context context, DatePickerDialog.OnDateSetListener callBack,
         * int year, int monthOfYear, int dayOfMonth)
         * content组件运行Activity，
         * DatePickerDialog.OnDateSetListener：选择日期事件
         * year：当前组件上显示的年，monthOfYear：当前组件上显示的月，dayOfMonth：当前组件上显示的第几天
         *
         */

        //显示系统日历(内部监听事件)
        DatePickerDialog datePickerDialog = new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

                //yyyy-MM-dd HH:mm:ss
                if (onSelectTimeCallBack != null) {
                    onSelectTimeCallBack.onSelectTimeDate(year + "-" + (month + 1) + "-" + dayOfMonth);
                }


            }
        }, mYear, mMonth, mDay);

        if (minTime) {
            //日历选择器能选的最小时间
            if (Build.VERSION.SDK_INT >= 11) {

                long currentTimeMillis = System.currentTimeMillis();
                DatePicker datePicker = datePickerDialog.getDatePicker();
                datePicker.setMinDate(currentTimeMillis);

            }
        }
        datePickerDialog.setTitle(null);
        datePickerDialog.show();


        //系统时间选择器
     /*       TimePickerDialog dialog = new TimePickerDialog(activity, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                    startcal.set(Calendar.HOUR_OF_DAY,hourOfDay);
                    startcal.set(Calendar.MINUTE, minute);

                    String date = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm").format(new java.util.Date(startcal.getTimeInMillis()));

                }
            },0,0,false);
            dialog.show();*/

        //单独设置点击事件
  /*      dpd.setButton(DialogInterface.BUTTON_POSITIVE, "确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //确定的逻辑代码在监听中实现
                        DatePicker picker = dpd.getDatePicker();
                        int year = picker.getYear();
                        int month = picker.getMonth()+1;
                        int dayOfMonth = picker.getDayOfMonth();
                        if(onSelectTimeCallBack!=null)
                        {
                            onSelectTimeCallBack.onSelectTimeDate(year+"-"+month+"-"+dayOfMonth);
                        }
                    }
                });
        dpd.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //取消什么也不用做
                    }
                });*/

    }


    //加载更多
    public void loadMoreOrderData(List<T> list, BaseUiAdapter adapter, RefreshLayout mRefreshLayout) {

        if (list != null) {
            if (list.size() > 0) {
                adapter.addList(list);
                if (list.size() < 10) {
                    //说明没有数据加载了
                    mRefreshLayout.finishLoadMoreWithNoMoreData();
                }
            } else {
                //说明没有数据加载了(返回的size=0)
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            }
        }
        mRefreshLayout.finishLoadMore();

    }

    public String getImageSeverUrl(String url) {
        String urls = url;
        if (!TextUtils.isEmpty(url)) {
            //判断是否包含图片http前缀
            if (url.indexOf("http") != -1) {
                return urls;
            } else {
                //urls = SeverUrl.SEVER_IMAGE_URL + urls;
                return urls;
            }
        }
        return urls;
    }

    //刷新数据
    public void loadRefreshData(List<T> list, BaseUiAdapter adapter, RefreshLayout mRefreshLayout, NetworkLayout failnetworkd) {

        //刷新数据
        adapter.clear();
        if (list != null && list.size() > 0) {

            if (failnetworkd != null) {
                failnetworkd.setVisibility(View.GONE);
            }

            adapter.setList(list);
            GlobalTools.getInstance().logD("======list==" + list.size());
            if (list.size()<10){
                mRefreshLayout.setNoMoreData(true);
            } else {
                //还能加载更多
                mRefreshLayout.setEnableLoadMore(true);
                mRefreshLayout.setNoMoreData(false);
            }
        } else {
            if (failnetworkd != null) {
                failnetworkd.setVisibility(View.VISIBLE);
                failnetworkd.setEmtyLayout();
            }
        }
        mRefreshLayout.finishRefresh();


    }

    //跳转到图片预览界面
    public void gotoLook(Activity base, ArrayList<ImageInfo> imageInfo, int position, boolean show, View view, boolean single) {

        if (single) {

            for (int i = 0; i < imageInfo.size(); i++) {
                ImageInfo info = imageInfo.get(i);
//            View imageView;
//            if (i < nineGridView.getMaxSize()) {
//                imageView = nineGridView.getChildAt(i);
//            } else {
//                //如果图片的数量大于显示的数量，则超过部分的返回动画统一退回到最后一个图片的位置
//                imageView = nineGridView.getChildAt(nineGridView.getMaxSize() - 1);
//            }
                info.imageViewWidth = view.getWidth();
                info.imageViewHeight = view.getHeight();

                int[] points = new int[2];
                view.getLocationInWindow(points);
                info.imageViewX = points[0];
                info.imageViewY = points[1] - getStatusBarHeight(base);

            }
        }


        Intent intent = new Intent(base, ImagePreviewActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(ImagePreviewActivity.IMAGE_INFO, (Serializable) imageInfo);
        bundle.putInt(ImagePreviewActivity.CURRENT_ITEM, position);
        bundle.putBoolean(ImagePreviewActivity.BOOLEANSHOW, show);
        intent.putExtras(bundle);
        base.startActivity(intent);
        base.overridePendingTransition(0, 0);
    }


    public Html.ImageGetter getImageGetter() {
        //这里面的resource就是fromhtml函数的第一个参数里面的含有的url
        Html.ImageGetter imgGetter = new Html.ImageGetter() {
            public Drawable getDrawable(String source) {
                Log.i("RG", "source---?>>>" + source);
                Drawable drawable = null;
                URL url;
                try {
                    url = new URL(source);
                    Log.i("RG", "url---?>>>" + url);
                    drawable = Drawable.createFromStream(url.openStream(), ""); // 获取网路图片
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                        drawable.getIntrinsicHeight());
                Log.i("RG", "url---?>>>" + url);
                return drawable;
            }
        };
        return imgGetter;
    }

    //短信倒计时
    public CountDownTimer getCountDownTimer(final Context context, final View view, final TextView textView) {
        CountDownTimer mCountDownTimer = new CountDownTimer(60000, 100) {
            @Override
            public void onTick(long millisUntilFinished) {
                view.setEnabled(false);
                textView.setText(millisUntilFinished / 1000 + context.getString(R.string.GetCode_s));
            }

            @Override
            public void onFinish() {
                textView.setText(context.getString(R.string.huoquyanzhen));
                view.setEnabled(true);
            }
        };
        return mCountDownTimer;
    }

    public void setWXsharedPreferences(Context context,int erroCode)
    {
        SharedPreferences sp = context.getSharedPreferences("WX_code", Context.MODE_PRIVATE);
        sp.edit().putInt("wx_erro_code",erroCode).commit();

    }

    //获取微信支付结果
    public int getWXsharedPreferences(Context context)
    {
        SharedPreferences sp = context.getSharedPreferences("WX_code", Context.MODE_PRIVATE);
        int wx_erro_code = sp.getInt("wx_erro_code", -3);
        return  wx_erro_code;
    }





    /**
     * 生成微信支付参数
     */
   /* public void startWxPay(Activity activity, WxPayData data)
    {
        PayReq req = new PayReq();
        req.appId = data.getAppid();
        req.partnerId = data.getPartnerid();
        req.prepayId = data.getPrepayid();
        req.packageValue = data.getPackages();
        req.nonceStr = data.getNoncestr();
        req.timeStamp = data.getTimestamp();
        req.sign = data.getSign();

        IWXAPI msgApi = WXAPIFactory.createWXAPI(activity, Constants.APP_ID);
        boolean register = msgApi.registerApp(req.appId);
        if (!register)
        {
            showToast(activity, "调用微信失败!");
        }
        boolean sendReq = msgApi.sendReq(req);
        if (!sendReq)
        {
            showToast(activity, "支付发起失败，请检查是否安装微信客户端!");
        }
    }*/


   /* public String getImageSeverUrl(String url)
    {
        String urls = url;
        if (!TextUtils.isEmpty(url))
        {
            //判断是否包含图片http前缀
            if (url.indexOf("http") != -1)
            {
                return urls;
            } else
            {
                urls = SeverUrl.SEVER_URL+ urls;
                return urls;
            }
        }
        return urls;
    }*/

}
